package org.samith.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.samith.dao.UserDao;
import org.samith.entity.User;
import org.samith.web.helper.AuthenticatedUserSession;
import org.samith.web.helper.DigestAlgorithm;

public class ChangePasswordServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@EJB
	UserDao userDao;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = getServletConfig().getServletContext();
		context.getRequestDispatcher("/ChangePassword/index.jsp").forward(
				request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String currentPassword = request.getParameter("userPass");
		String passcode = request.getParameter("userPassNew");
		String passcodeConfirmed = request.getParameter("userPassNewConfirm");
		HttpSession session = request.getSession();
		AuthenticatedUserSession userSession = (AuthenticatedUserSession) session
				.getAttribute("authenticatedUser");
		Long userId = userSession.getUserId();
		User user = userDao.findById(userId);
		if (user.getPassword().equals(
				DigestAlgorithm.getSHA1Digest(currentPassword))
				&& passcode.equals(passcodeConfirmed)) {
			user.setPassword(DigestAlgorithm.getSHA1Digest(passcode));
			userDao.update(user);
			session.setAttribute("authenticatedUser", null);
			response.sendRedirect("/ejbApp/login");
		} else {
			response.sendRedirect("/ejbApp/changePassword");
		}

	}
}